package com.example.administrator.yanfoxconn.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.DNReformAdapter;
import com.example.administrator.yanfoxconn.adapter.EmpListAdapter;
import com.example.administrator.yanfoxconn.bean.KOInfo;
import com.example.administrator.yanfoxconn.bean.LRMessage;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyListView;
import com.example.administrator.yanfoxconn.widget.SwipeListViewOne;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.zxing.qrcode.encoder.QRCode;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Song
 * on 2022/03/10
 * Description：車輛排配
 */
public class LRSearchListActivity extends BaseActivity implements View.OnClickListener {
    private final int MESSAGE_SET_LIST = 1;//掃描成功賦值
    private final int MESSAGE_TOAST = 2;//掃描失敗彈出框
    private final int MESSAGE_ALERT = 4;//掃描失敗彈出框
    private final int MESSAGE_SET_SEARCH_LIST = 3;//提交信息回復
    private final int MESSAGE_NETMISTAKE = 5;//網絡錯誤
    private final int MESSAGE_SET_MT_LIST = 6;//碼頭列表



    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題

    @BindView(R.id.ll_tr)
    LinearLayout llTR;//查詢條件部分
    @BindView(R.id.et_mt)
    EditText etMT;//碼頭
     @BindView(R.id.tr_list_mt)
    TableRow trListMT;//碼頭
    @BindView(R.id.lv_mt)
    MyListView lvMT;//碼頭
    @BindView(R.id.et_car)
    EditText etCar;//車牌號
    @BindView(R.id.btn_one)
    Button btnCheck;//查詢
    @BindView(R.id.lv_normal)
    MyListView lvNormal;
    @BindView(R.id.ll_lr)
    LinearLayout llLR;

    private DNReformAdapter dnReformAdapter;
    private List<LRMessage> mtInfoList,lrSearchList;

    private String flag,pId,pNum;//flag:SH收貨,FH發貨
    private Date curDate = null;//當前時間
    private SimpleDateFormat formatter;
    private String outTime;
    private List<String> teamList;
    private EmpListAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lr_lv);
        ButterKnife.bind(this);
        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat formatterUse = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        curDate = new Date(System.currentTimeMillis());
        //获取当前时间
        outTime = formatter.format(curDate);
        tvTitle.setText(getIntent().getStringExtra("title"));
        btnBack.setOnClickListener(this);
        btnCheck.setOnClickListener(this);
        flag = getIntent().getStringExtra("flag");
        if (flag.equals("FH")) {
            tvTitle.setText("裝貨列表");
        }else if (flag.equals("SH")){
            tvTitle.setText("卸貨列表");
        }
        baseInfoByFlag( flag);

        etMT.setTag("0");//用於判斷是否選擇門崗0;為未選擇,其他為選擇
        //搜索关键字
        etMT.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                trListMT.setVisibility(View.VISIBLE);
                String a = etMT.getText().toString().toUpperCase();
                //调用适配器里面的搜索方法
                mAdapter.SearchCity(a);
            }
            @Override
            public void afterTextChanged(Editable editable) {
            }

        });
        lvNormal.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                pId= lrSearchList.get(position).getPID();
                pNum= lrSearchList.get(position).getPALLETNUM();
                FoxContext.getInstance().setPALLETNUM(lrSearchList.get(position).getPALLETNUM());
                if (flag.equals("FH")){
                    if (lrSearchList.get(position).getSTATUS().equals("1")){
                        Intent resultIntent = new Intent(LRSearchListActivity.this, LRPalletListActivity.class);
                        resultIntent.putExtra("result", "");
                        resultIntent.putExtra("pId", pId);
                        resultIntent.putExtra("pNum", pNum);
                        resultIntent.putExtra("flag", "FH");
                        startActivity(resultIntent);
                    }else{
                      aboutAlert("開始裝貨", MESSAGE_ALERT);
                    }
                }else{
                    if (lrSearchList.get(position).getSTATUS().equals("2")){
                        Intent resultIntent = new Intent(LRSearchListActivity.this, LRPalletListActivity.class);
                        resultIntent.putExtra("result", "");
                        resultIntent.putExtra("pId", pId);
                        resultIntent.putExtra("pNum", pNum);
                        resultIntent.putExtra("flag", "SH");
                        resultIntent.putExtra("build",etMT.getText().toString());
                        startActivity(resultIntent);
                    }else{
                        aboutAlert("開始卸貨", MESSAGE_ALERT);
                    }
                }
            }
        });
    }

    /**
     * 用於解決scrollview嵌套listview導致只顯示一條數據的問題
     *
     * @param listView
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        DNReformAdapter listAdapter = (DNReformAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_title_left://返回
                finish();
                break;
            case R.id.btn_one://查詢
                getSearch(etMT.getText().toString(),etCar.getText().toString(),flag);
                break;
        }
    }



    private String url2 = "";

    private void baseInfoByFlag(String flag){
url2=Constants.HTTP_LR_BASEINFOBYFLAG + "?flag="+flag;
        Log.e("---------", "url2==fff===" + url2);
        showDialog();
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        mtInfoList = new ArrayList<LRMessage>();

                        for (JsonElement type : array) {
                            LRMessage humi = gson.fromJson(type, LRMessage.class);
                            mtInfoList.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_MT_LIST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else {
                        Log.e("-----------", "result==" + result);
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    //賦值碼頭別表
    private void setMtList(){
        teamList = new ArrayList<>();
        for (int i = 0;i<mtInfoList.size();i++){
            teamList.add(mtInfoList.get(i).getNAME());
        }

        mAdapter = new EmpListAdapter(LRSearchListActivity.this,teamList,"lr");
        lvMT.setAdapter(mAdapter);

        //稽核門崗列表,選中后1:tit賦值,2:列表隱藏
        mAdapter.OnClickSetText(new EmpListAdapter.OnClickSetText() {
            @Override
            public void OnClickxt(String tit) {
                etMT.setText(tit);
                etMT.setTag(tit);
//                paramMap.put("mengang", empFileList.get(position).getID());
                mAdapter.SearchCity("");
                trListMT.setVisibility(View.GONE);
            }
            @Override
            public void OnClicktv(String tit, String tv) {
            }
        });
    }
    //更新指定單號狀態
    private void carStatusUp(String pId,String status,String creator){
        try {
            String status1 =  URLEncoder.encode(URLEncoder.encode(status, "UTF-8"), "UTF-8");
            String creator1 =  URLEncoder.encode(URLEncoder.encode(creator, "UTF-8"), "UTF-8");

            url2=Constants.HTTP_LR_CARSTATUSUP + "?pId="+pId+"&status="+status1+"&creator="+creator1;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.e("---------", "url2==fff===" + url2);
        showDialog();
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {

                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errCode").getAsString();
                        mHandler.sendMessage(message);

                    } else {
                        Log.e("-----------", "result==" + result);
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    private void getSearch(String c_area,String c_car,String flag){
        try {
            String c_area1 =  URLEncoder.encode(URLEncoder.encode(c_area.toString(), "UTF-8"), "UTF-8");
            String c_car1 =  URLEncoder.encode(URLEncoder.encode(c_car.toString(), "UTF-8"), "UTF-8");

            url2=Constants.HTTP_LR_CARINFO + "?flag="+flag+"&area="+c_area1+"&carNum="+c_car1;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.e("---------", "url2==fff===" + url2);
        showDialog();
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        lrSearchList = new ArrayList<LRMessage>();

                        for (JsonElement type : array) {
                            LRMessage humi = gson.fromJson(type, LRMessage.class);
                            lrSearchList.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_SEARCH_LIST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else {
                        Log.e("-----------", "result==" + result);
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_TOAST://Toast彈出
                    if (msg.obj.toString().equals("200")){
                        if (flag.equals("FH")){
                        Intent intent=new Intent(LRSearchListActivity.this, QrCodeActivity.class);
                        intent.putExtra("flag",flag);
                        intent.putExtra("num","LR");
                        intent.putExtra("no",pId);
                        intent.putExtra("pNum",pNum);
                        startActivity(intent);
                        }else{
                            Intent resultIntent = new Intent(LRSearchListActivity.this, LRPalletListActivity.class);
                            resultIntent.putExtra("result", "");
                            resultIntent.putExtra("pId", pId);
                            resultIntent.putExtra("pNum", pNum);
                            resultIntent.putExtra("flag", "SH");
                            resultIntent.putExtra("build",etMT.getText().toString());
                            startActivity(resultIntent);
                        }
                    }else{

                        ToastUtils.showLong(LRSearchListActivity.this, msg.obj.toString());
                        if (lrSearchList!=null){
                            lrSearchList.clear();
                        dnReformAdapter = new DNReformAdapter(LRSearchListActivity.this, lrSearchList, "LR",flag);
                        lvNormal.setAdapter(dnReformAdapter);}
//                        aboutAlert(msg.obj.toString(), MESSAGE_TOAST);
                    }
                    break;
                case MESSAGE_NETMISTAKE://Toast彈出
                    ToastUtils.showLong(LRSearchListActivity.this, R.string.net_mistake);
                    break;
//                case MESSAGE_SET_LIST://進度賦值
////                    dnReformAdapter = new DNReformAdapter(LRSearchListActivity.this, koInfoList, "KO");
//                    listView.setAdapter(dnReformAdapter);
//                    setListViewHeightBasedOnChildren(listView);
//                    clickSeeOrAdd();
//                    break;
                case MESSAGE_SET_SEARCH_LIST://樓棟賦值
                    dnReformAdapter = new DNReformAdapter(LRSearchListActivity.this, lrSearchList, "LR",flag);
                    lvNormal.setAdapter(dnReformAdapter);
                    setListViewHeightBasedOnChildren(lvNormal);
                    break;
                case MESSAGE_SET_MT_LIST://賦值碼頭別表
                    setMtList();
                    break;
//                case MESSAGE_SET_FLOOR://樓層賦值
//                    setFloor();
//                    break;
//                case MESSAGE_SET_ROOM://區域賦值
//                    setRoom();
//                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void aboutAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setNeutralButton("取消", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub}
                    }  })
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type == MESSAGE_ALERT) {
                            if (flag.equals("FH")){
                            carStatusUp(pId,"開始裝貨",FoxContext.getInstance().getName());
                            }else{

                                carStatusUp(pId,"開始卸貨",FoxContext.getInstance().getName());
                            }

                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!etMT.getText().toString().equals("")&&!etCar.getText().toString().equals("")) {
            getSearch(etMT.getText().toString(),etCar.getText().toString(),flag);
        }
    }
}